package filter

import (
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/beego/beego/v2/server/web/context"
	"regexp"
	"strings"
	"xpms/app/asset"
)

func RootTree() beego.FilterFunc {
	return func(ctx *context.Context) {
		ctx.ResponseWriter.Header().Add("Content-Type", "text/html; charset=utf-8")
		//http.ServeFile(ctx.ResponseWriter, ctx.Request, "view/")
		bytes, err := asset.Asset("view/index.html") // 根据地址获取对应内容
		if err != nil {
			fmt.Println("出现错误", err)
			return
		}
		str := string(bytes[:])
		ctx.WriteString(str)
	}
}
func TransparentStatic() beego.FilterFunc {
	return func(ctx *context.Context) {
		url := ctx.Request.URL.Path
		fmt.Print(url)
		reg := regexp.MustCompile("css|js|fonts|img")
		res := reg.FindAllString(url, -1)
		//fmt.Println(res)

		if nil == res {
			ctx.ResponseWriter.Header().Add("Content-Type", "text/html; charset=utf-8")
			bytes, err := asset.Asset("view/index.html") // 根据地址获取对应内容
			if err != nil {
				fmt.Println("出现错误", err)
				return
			}
			str := string(bytes[:])
			ctx.WriteString(str)
			//http.ServeFile(ctx.ResponseWriter, ctx.Request, "view/")
		} else {
			w := strings.Split(url, "/")
			a := len(w)
			if "" == w[0] && "" == w[a-1] {
				w = w[1 : len(w)-1]
			} else {
				fmt.Print(w)
				if "" == w[0] && "" != w[a-1] {
					w = w[1:]
				} else if "" != w[0] && "" == w[a-1] {
					w = w[0:(a - 1)]
				}
			}
			ww := strings.Join(w, "/")
			ww = "view/" + ww
			bytes, err := asset.Asset(ww) // 根据地址获取对应内容
			if err != nil {
				fmt.Println("出现错误", err)
				return
			}
			str := string(bytes[:])
			if "img" == res[0] {
				ctx.ResponseWriter.Header().Add("Content-Type", "image/png")
				_, _ = ctx.ResponseWriter.Write(bytes)
			} else {
				if "css" == res[0] {
					ctx.ResponseWriter.Header().Add("Content-Type", "text/css")
				}
				if "js" == res[0] {
					ctx.ResponseWriter.Header().Add("Content-Type", "application/javascript")
				}
				ctx.WriteString(str)
			}
		}
	}
}
